import React, { useEffect, useRef, useState } from 'react';
import { Container, Row, Col, Button, Card, Alert } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import io from 'socket.io-client';

function App() {
  const videoRef = useRef(null);
  const [stats, setStats] = useState({ fire: 0, smoke: 0, fps: 0 });
  const [isDetecting, setIsDetecting] = useState(false);
  const [error, setError] = useState(null);
  const [cameraReady, setCameraReady] = useState(false);
  const [statusMessage, setStatusMessage] = useState("等待启动检测");
  const [isConnected, setIsConnected] = useState(false);
  const [startTimeout, setStartTimeout] = useState(null);
  
  // 使用ref存储socket实例
  const socketRef = useRef(null);

  useEffect(() => {
    // 创建Socket.IO连接
    const socket = io('http://localhost:5000', {
      reconnection: true,
      reconnectionAttempts: 10,
      reconnectionDelay: 3000,
      transports: ['websocket', 'polling'],
      withCredentials: true
    });
    
    socketRef.current = socket;

    // 监听检测统计
    socket.on('detection_stats', (data) => {
      setStats(data);
    });
    
    // 监听状态变化
    socket.on('status', (data) => {
      if (data.status === 'detection_started') {
        setIsDetecting(true);
        setStatusMessage("检测已启动，正在初始化视频流...");
        setCameraReady(true);
        // 添加时间戳避免缓存问题
        const timestamp = new Date().getTime();
        if (videoRef.current) {
          videoRef.current.src = `http://localhost:5000/video_feed?t=${timestamp}`;
        }
      } else if (data.status === 'detection_stopped') {
        setIsDetecting(false);
        setCameraReady(false);
        setStatusMessage("检测已停止");
      } else if (data.status === 'already_running') {
        setStatusMessage("检测已在运行中");
      }
    });

    // 监听错误
    socket.on('error', (data) => {
      setError(data.message);
      setIsDetecting(false);
      setCameraReady(false);
      setStatusMessage(`错误: ${data.message}`);
      if (startTimeout) {
        clearTimeout(startTimeout);
        setStartTimeout(null);
      }
    });

    // 连接事件
    socket.on('connect', () => {
      console.log('已连接到后端服务器');
      setIsConnected(true);
      setStatusMessage("已连接到后端服务器");
    });

    // 断开连接事件
    socket.on('disconnect', (reason) => {
      console.log(`与后端服务器断开连接: ${reason}`);
      setIsConnected(false);
      setError('与服务器断开连接');
      setStatusMessage(`连接断开: ${reason}`);
      
      // 尝试重新连接
      if (reason === 'io server disconnect') {
        setTimeout(() => {
          console.log('尝试重新连接...');
          socket.connect();
        }, 3000);
      }
    });

    // 连接错误事件
    socket.on('connect_error', (err) => {
      console.error('连接错误:', err.message);
      setIsConnected(false);
      setError(`无法连接到服务器: ${err.message}`);
      setStatusMessage(`连接错误: ${err.message}`);
      
      // 尝试重新连接
      setTimeout(() => {
        console.log('尝试重新连接...');
        socket.connect();
      }, 5000);
    });

    return () => {
      if (socketRef.current) {
        socketRef.current.disconnect();
      }
      
      if (startTimeout) {
        clearTimeout(startTimeout);
      }
    };
  }, []);

  const startDetection = () => {
    if (!socketRef.current || !socketRef.current.connected) {
      setError("未连接到后端服务器，请稍后再试");
      setStatusMessage("后端连接不可用");
      return;
    }
    
    setError(null);
    setStatusMessage("正在启动检测...");
    
    // 设置10秒超时
    const timeout = setTimeout(() => {
      if (!isDetecting && !cameraReady) {
        setError("启动检测超时，请检查后端服务和摄像头连接");
        setStatusMessage("启动超时");
      }
    }, 10000);
    
    setStartTimeout(timeout);
    socketRef.current.emit('start_detection');
  };

  const stopDetection = () => {
    if (socketRef.current && socketRef.current.connected) {
      socketRef.current.emit('stop_detection');
    }
    setStatusMessage("正在停止检测...");
    if (startTimeout) {
      clearTimeout(startTimeout);
      setStartTimeout(null);
    }
  };

  const testConnection = () => {
    setError(null);
    setStatusMessage("正在测试后端连接...");
    
    // 简单的方法测试后端是否在线
    fetch('http://localhost:5000/')
      .then(response => {
        if (response.ok) {
          setStatusMessage("后端服务在线");
        } else {
          setError("后端服务无响应");
          setStatusMessage("后端服务无响应");
        }
      })
      .catch(err => {
        setError(`无法连接到后端: ${err.message}`);
        setStatusMessage(`连接失败: ${err.message}`);
      });
  };

  return (
    <Container fluid className="py-4">
      {error && (
        <Alert variant="danger" onClose={() => setError(null)} dismissible>
          {error}
        </Alert>
      )}
      
      <Row>
        <Col md={8}>
          <Card className="mb-4">
            <Card.Header as="h5">实时检测</Card.Header>
            <Card.Body>
              <div className="position-relative" style={{ backgroundColor: '#f0f0f0', minHeight: '480px' }}>
                {cameraReady ? (
                  <img 
                    ref={videoRef} 
                    alt="Detection Stream" 
                    className="img-fluid"
                    onError={(e) => {
                      console.error('视频流加载错误', e);
                      setError('无法加载视频流，请检查后端连接');
                      setStatusMessage("视频流加载错误");
                    }}
                  />
                ) : (
                  <div className="d-flex justify-content-center align-items-center" style={{ height: '480px' }}>
                    <div className="text-center">
                      <div className="spinner-border text-primary" role="status">
                        <span className="visually-hidden">加载中...</span>
                      </div>
                      <p className="mt-2">{statusMessage}</p>
                    </div>
                  </div>
                )}
                
                <div className="position-absolute top-0 end-0 bg-dark text-white p-2">
                  FPS: {stats.fps.toFixed(1)}
                </div>
              </div>
              <div className="mt-3">
                {isDetecting ? (
                  <Button variant="danger" onClick={stopDetection} disabled={!cameraReady}>
                    停止检测
                  </Button>
                ) : (
                  <Button variant="success" onClick={startDetection} disabled={isDetecting || !isConnected}>
                    {isDetecting ? "启动中..." : "开始检测"}
                  </Button>
                )}
                
                <Button 
                  variant="outline-secondary" 
                  className="ms-2"
                  onClick={() => {
                    setError(null);
                    setStatusMessage("正在重启检测...");
                    stopDetection();
                    setTimeout(startDetection, 500);
                  }}
                  disabled={!isConnected}
                >
                  重启检测
                </Button>
                
                <Button 
                  variant="outline-info" 
                  className="ms-2"
                  onClick={testConnection}
                >
                  测试连接
                </Button>
              </div>
            </Card.Body>
          </Card>
        </Col>
        
        <Col md={4}>
          <Card className="mb-4">
            <Card.Header as="h5">检测统计</Card.Header>
            <Card.Body>
              <div className="d-flex justify-content-between mb-3">
                <div className="text-center">
                  <h5>火焰</h5>
                  <div className="display-4 text-danger">{stats.fire}</div>
                </div>
                <div className="text-center">
                  <h5>烟雾</h5>
                  <div className="display-4 text-secondary">{stats.smoke}</div>
                </div>
              </div>
              
              <Card className="mt-4">
                <Card.Header>系统状态</Card.Header>
                <Card.Body>
                  <p>检测状态: 
                    <span className={isDetecting ? "text-success fw-bold" : "text-danger"}>
                      {isDetecting ? " 运行中" : " 已停止"}
                    </span>
                  </p>
                  <p>帧率: {stats.fps.toFixed(1)} FPS</p>
                  <p>视频状态: 
                    <span className={cameraReady ? "text-success fw-bold" : "text-warning"}>
                      {cameraReady ? " 已连接" : " 未连接"}
                    </span>
                  </p>
                  <p>后端连接: 
                    <span className={isConnected ? "text-success fw-bold" : "text-danger"}>
                      {isConnected ? " 已连接" : " 已断开"}
                    </span>
                  </p>
                  <p>状态信息: {statusMessage}</p>
                </Card.Body>
              </Card>
            </Card.Body>
          </Card>
          
          <Card className="mb-4">
            <Card.Header as="h5">操作指南</Card.Header>
            <Card.Body>
              <ol>
                <li>确保后端服务正在运行 (在终端运行 app.py)</li>
                <li>点击"测试连接"按钮确认前后端连接</li>
                <li>点击"开始检测"按钮启动摄像头</li>
                <li>确保摄像头未被其他程序占用</li>
                <li>如果出现问题，尝试"重启检测"按钮</li>
                <li>检查后端控制台查看详细日志</li>
              </ol>
              <div className="d-grid gap-2">
                <Button 
                  variant="outline-info" 
                  href="http://localhost:5000/test_camera" 
                  target="_blank"
                  className="mt-2"
                >
                  测试摄像头
                </Button>
                <Button 
                  variant="outline-dark" 
                  href="http://localhost:5000/" 
                  target="_blank"
                  className="mt-2"
                >
                  访问后端首页
                </Button>
              </div>
            </Card.Body>
          </Card>
        </Col>
      </Row>
    </Container>
  );
}

export default App;